// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
/**
 * 引用element-UI
 * 1.cmd执行npm i element-ui -S  全局安装
 * 2.main.js文件加入：
 * 
 * import ElementUI from 'element-ui';
 * import 'element-ui/lib/theme-chalk/index.css';
 * Vue.use(ElementUI);
 */
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.config.productionTip = false
Vue.use(VueAxios, axios)

/**
 * 定义全局变量
 */
import global from './Global.vue' //引用文件
Vue.prototype.GLOBAL = global //挂载到Vue实例上面
//定义全局方法
import common from './common.js'
Vue.prototype.COMMON = common


Vue.use(ElementUI);
Vue.config.productionTip = false

import './directives.js';

let isFetchRemote = true;
import routeMap from './components.js';
//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
  // 获取所有路由信息
  var routers = router.getRoutes();
  // 如果路由表中包含则直接访问
  for(var i = 0;i<routers.length;i++){
    var e = routers[i];
    if(e.path === to.path){
      next();
      return ;
    }
  }
  if (isFetchRemote && to.path !== '/login' && to.path !== '/') {// 获取路由信息
    var user = JSON.parse(localStorage.user);
    axios
      .post(global.BASE_URL + 'routeOperation/getRoutes', user)
      .then(res => {
        if (res.status === 200 && res.data.result === "SUCCESS") {
          isFetchRemote = false;
          const menuData = res.data.data;
          const routeData = formatRoutes(menuData);
          routeData.forEach(route => {
            router.addRoute("Home", route);
          });
          router.push({
            path: to.path,
            query: to.query
          });
          next();
        } else {
          isFetchRemote = true;
          next({
            path: '/login'
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  } else {
    next();
  }
});

const formatRoutes = function (routeData) {
  routeData.childrens.forEach(route => {
    if (route.componentName) {
      route.component = routeMap[route.componentName];
    }
  });
  return routeData.childrens;
};

import store from './store/store';
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {
    App
  },
  template: '<App/>',
  store
})
